import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import 'package:stacked/stacked.dart';
import 'package:vista/app/di/injection.dart';
import 'package:vista/shared/constants/color.dart';
import 'package:vista/features/message/viewmodels/group_chat_viewmodel.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/services/circle_gallery.dart';
import 'package:vista/shared/models/group_message.dart';
import 'package:vista/shared/models/user_frame.dart';
import 'package:vista/shared/widgets/complain_bottom_sheet.dart';
import 'package:vista/shared/utils/flash_notifier.dart';

/// 群聊视图
/// 显示与某个群组的对话
class GroupChatView extends StatelessWidget {
  final String groupId;

  const GroupChatView({super.key, required this.groupId});

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<GroupChatViewModel>.reactive(
      viewModelBuilder:
          () => GroupChatViewModel(
            getIt.get<AuthFocus>(),
            getIt.get<CircleGallery>(),
            groupId,
          )..initialize(),
      builder: (context, viewModel, child) {
        return Scaffold(
          body: Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [const Color(0xFFFFEBE6), const Color(0xFFFFA680)],
              ),
            ),
            child: SafeArea(
              bottom: false,
              child: Column(
                children: [
                  // 顶部标题栏
                  _buildHeader(context, viewModel),
                  // 群组信息栏
                  if (viewModel.currentGroup != null)
                    _buildGroupInfoBar(context, viewModel),
                  // 聊天消息列表
                  Expanded(
                    child:
                        viewModel.isBusy
                            ? const Center(child: CircularProgressIndicator())
                            : viewModel.currentUser == null
                            ? const Center(child: Text('Please login'))
                            : _buildMessageList(context, viewModel),
                  ),
                  // 底部输入栏
                  _buildInputBar(context, viewModel),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  /// 构建顶部标题栏
  Widget _buildHeader(BuildContext context, GroupChatViewModel viewModel) {
    return Container(
      padding: EdgeInsets.only(left: 14.w, right: 14.w, bottom: 12.h),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(color: Colors.black.withOpacity(0.1), width: 1),
        ),
      ),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Icon(
              Icons.chevron_left_rounded,
              size: 28.w,
              color: Colors.black87,
            ),
          ),
          SizedBox(width: 12.w),
          // 标题
          Expanded(
            child: Center(
              child: Text(
                viewModel.currentGroup?.title ?? 'Information',
                style: TextStyle(
                  fontSize: 20.sp,
                  fontFamily:
                      GoogleFonts.alegreyaSans(
                        fontWeight: FontWeight.w800,
                      ).fontFamily,
                  color: Colors.black87,
                ),
              ),
            ),
          ),
          SizedBox(width: 12.w),
          // 举报按钮
          GestureDetector(
            onTap: () {
              ComplainHelper.unveil(
                context,
                onComplain: (reason) async {
                  // 举报后删除所有消息并返回
                  await viewModel.deleteAllMessages();
                  // 显示举报成功提示
                  FlashNotifier.flashSuccess('Report submitted successfully');
                  if (context.mounted) {
                    Navigator.of(context).pop();
                  }
                },
              );
            },
            child: Container(
              width: 32.w,
              height: 32.w,
              padding: EdgeInsets.all(4.w),
              decoration: BoxDecoration(shape: BoxShape.circle),
              child: Image.asset('assets/images/report.png'),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建群组信息栏
  Widget _buildGroupInfoBar(
    BuildContext context,
    GroupChatViewModel viewModel,
  ) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 14.w, vertical: 14.h),
      height: 58.h,
      padding: EdgeInsets.symmetric(horizontal: 6.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8.r),
        border: Border.all(color: Colors.black, width: 1),
        boxShadow: [
          // 右边框阴影
          BoxShadow(
            color: Colors.black,
            offset: Offset(2.w, 0),
            blurRadius: 0,
            spreadRadius: 0,
          ),
          // 下边框阴影
          BoxShadow(
            color: Colors.black,
            offset: Offset(0, 2.h),
            blurRadius: 0,
            spreadRadius: 0,
          ),
        ],
      ),
      child: Row(
        children: [
          // 群聊图片
          Container(
            width: 46.w,
            height: 46.w,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(8.r),
              image:
                  viewModel.currentGroup?.image != null
                      ? DecorationImage(
                        image: AssetImage(viewModel.currentGroup!.image),
                        fit: BoxFit.contain,
                      )
                      : null,
              color: Colors.transparent,
            ),
            child:
                viewModel.currentGroup?.image == null
                    ? Icon(Icons.group, size: 23.w, color: Colors.grey)
                    : null,
          ),
          SizedBox(width: 14.w),
          // 群聊名称
          Expanded(
            child: Text(
              viewModel.currentGroup?.title ?? 'Group',
              style: TextStyle(
                fontSize: 16.sp,
                fontFamily:
                    GoogleFonts.alegreyaSans(
                      fontWeight: FontWeight.w800,
                    ).fontFamily,
                color: Colors.black87,
              ),
            ),
          ),
          SizedBox(width: 14.w),
          // 用户头像叠层
          _buildAvatarStack(viewModel),
          SizedBox(width: 14.w),
          // 退出群聊按钮
          GestureDetector(
            onTap: () {
              _showLeaveGroupDialog(context, viewModel);
            },
            child: Container(
              width: 44.w,
              height: 44.w,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8.r),
                color: ColorConstants.primaryColor,
              ),
              padding: EdgeInsets.all(10.w),
              child: Image.asset('assets/images/quit.png', fit: BoxFit.contain),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建头像叠层
  Widget _buildAvatarStack(GroupChatViewModel viewModel) {
    // 最多显示4个头像，超过4个显示一个额外的圆圈
    final displayMembers = viewModel.members.take(4).toList();
    final hasMore = viewModel.members.length > 4;

    return SizedBox(
      width:
          18.w +
          (displayMembers.length - 1) * 12.w +
          (hasMore ? 12.w + 18.w : 0),
      height: 18.w,
      child: Stack(
        children: [
          ...displayMembers.asMap().entries.map((entry) {
            final index = entry.key;
            final member = entry.value;
            return Positioned(
              left: index * 12.w,
              child: Container(
                width: 18.w,
                height: 18.w,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  border: Border.all(color: Colors.white, width: 1.w),
                ),
                child: CircleAvatar(
                  radius: 8.5.r,
                  backgroundColor: Colors.white,
                  backgroundImage:
                      member.avatar != null ? AssetImage(member.avatar!) : null,
                  child:
                      member.avatar == null
                          ? Icon(Icons.person, size: 9.w, color: Colors.grey)
                          : null,
                ),
              ),
            );
          }),
          if (hasMore)
            Positioned(
              left: displayMembers.length * 12.w,
              child: Container(
                width: 18.w,
                height: 18.w,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  border: Border.all(color: Colors.white, width: 1.w),
                  color: ColorConstants.primaryColor,
                ),
                child: Center(
                  child: Text(
                    '+${viewModel.members.length - 4}',
                    style: TextStyle(
                      fontSize: 8.sp,
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }

  /// 显示退出群组确认弹窗
  void _showLeaveGroupDialog(
    BuildContext context,
    GroupChatViewModel viewModel,
  ) {
    showDialog(
      context: context,
      builder:
          (context) => Dialog(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(24.r),
            ),
            insetPadding: EdgeInsets.symmetric(
              horizontal: 40.w,
              vertical: 80.h,
            ),
            elevation: 0,
            backgroundColor: Colors.transparent,
            child: Container(
              constraints: BoxConstraints(maxWidth: 320.w, minWidth: 280.w),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(24.r),
                gradient: LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  colors: [const Color(0xFFFFA680), const Color(0xFFFFEBE6)],
                ),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 20.w,
                    offset: Offset(0, 10.h),
                  ),
                ],
              ),
              child: Padding(
                padding: EdgeInsets.all(36.w),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    // 标题
                    Text(
                      'Leave Group',
                      style: TextStyle(
                        fontSize: 24.sp,
                        fontWeight: FontWeight.w800,
                        fontFamily:
                            GoogleFonts.alegreyaSans(
                              fontWeight: FontWeight.w800,
                            ).fontFamily,
                        color: Colors.black87,
                      ),
                    ),
                    SizedBox(height: 16.h),
                    // 描述
                    Text(
                      'Are you sure you want to leave ${viewModel.currentGroup?.title ?? 'this group'}?',
                      style: TextStyle(
                        fontSize: 16.sp,
                        color: Colors.black.withOpacity(0.7),
                        height: 1.5,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    SizedBox(height: 36.h),
                    // 按钮组
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        // 取消按钮
                        Expanded(
                          child: OutlinedButton(
                            onPressed: () => Navigator.of(context).pop(false),
                            style: OutlinedButton.styleFrom(
                              padding: EdgeInsets.symmetric(vertical: 16.h),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(12.r),
                              ),
                              side: BorderSide(
                                color: Colors.black.withOpacity(0.2),
                                width: 1.5,
                              ),
                            ),
                            child: Text(
                              'Cancel',
                              style: TextStyle(
                                fontSize: 16.sp,
                                fontWeight: FontWeight.w600,
                                color: Colors.black87,
                              ),
                            ),
                          ),
                        ),
                        SizedBox(width: 14.w),
                        // 确认按钮
                        Expanded(
                          child: ElevatedButton(
                            onPressed: () async {
                              Navigator.of(context).pop(true);
                              await viewModel.leaveGroup();
                              if (context.mounted) {
                                // 显示退出成功提示
                                FlashNotifier.flashSuccess(
                                  'Left group successfully',
                                );
                                Navigator.of(context).pop();
                              }
                            },
                            style: ElevatedButton.styleFrom(
                              padding: EdgeInsets.symmetric(vertical: 16.h),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(12.r),
                              ),
                              backgroundColor: Colors.black87,
                              foregroundColor: Colors.white,
                              elevation: 0,
                            ),
                            child: Text(
                              'Leave',
                              style: TextStyle(
                                fontSize: 16.sp,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
    );
  }

  /// 构建消息列表
  Widget _buildMessageList(BuildContext context, GroupChatViewModel viewModel) {
    if (viewModel.messages.isEmpty) {
      return Center(
        child: Text(
          'No messages yet',
          style: TextStyle(
            fontSize: 16.sp,
            color: Colors.black.withOpacity(0.5),
          ),
        ),
      );
    }

    return ListView.builder(
      padding: EdgeInsets.all(14.w),
      reverse: false,
      itemCount: viewModel.messages.length,
      itemBuilder: (context, index) {
        final message = viewModel.messages[index];
        final isCurrentUser = message.userId == viewModel.currentUser?.id;
        return FutureBuilder<UserFrame?>(
          future: viewModel.getSenderUser(message.userId),
          builder: (context, snapshot) {
            final senderUser = snapshot.data;
            return _buildMessageItem(
              context,
              viewModel,
              message,
              isCurrentUser,
              senderUser,
            );
          },
        );
      },
    );
  }

  /// 构建消息项
  Widget _buildMessageItem(
    BuildContext context,
    GroupChatViewModel viewModel,
    GroupMessage message,
    bool isCurrentUser,
    UserFrame? senderUser,
  ) {
    final timeStr = DateFormat('HH:mm').format(message.timestamp);
    final user = isCurrentUser ? viewModel.currentUser : senderUser;

    return Padding(
      padding: EdgeInsets.only(bottom: 14.h),
      child: Column(
        crossAxisAlignment:
            isCurrentUser ? CrossAxisAlignment.end : CrossAxisAlignment.start,
        children: [
          // 消息气泡行（头像和气泡底部对齐）
          Row(
            mainAxisAlignment:
                isCurrentUser ? MainAxisAlignment.end : MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              if (!isCurrentUser) ...[
                // 对方头像
                SizedBox(
                  width: 46.w,
                  height: 46.w,
                  child: CircleAvatar(
                    radius: 23.r,
                    backgroundColor: Colors.white,
                    backgroundImage:
                        user?.avatar != null ? AssetImage(user!.avatar!) : null,
                    child:
                        user?.avatar == null
                            ? Icon(Icons.person, size: 23.w, color: Colors.grey)
                            : null,
                  ),
                ),
                SizedBox(width: 8.w),
              ],
              // 消息气泡
              Container(
                constraints: BoxConstraints(maxWidth: 280.w),
                padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
                decoration: BoxDecoration(
                  color:
                      isCurrentUser ? ColorConstants.accentColor : Colors.white,
                  borderRadius:
                      isCurrentUser
                          ? BorderRadius.only(
                            topLeft: Radius.circular(12.r),
                            topRight: Radius.circular(12.r),
                            bottomLeft: Radius.circular(12.r),
                            bottomRight: Radius.circular(0),
                          )
                          : BorderRadius.only(
                            topLeft: Radius.circular(12.r),
                            topRight: Radius.circular(12.r),
                            bottomLeft: Radius.circular(0),
                            bottomRight: Radius.circular(12.r),
                          ),
                ),
                child: Text(
                  message.content,
                  style: TextStyle(
                    fontSize: 12.sp,
                    fontFamily:
                        GoogleFonts.notoSans(
                          fontWeight: FontWeight.w400,
                        ).fontFamily,
                    color: isCurrentUser ? Colors.white : Colors.black87,
                    height: 1.50,
                  ),
                ),
              ),
              if (isCurrentUser) ...[
                SizedBox(width: 8.w),
                // 当前用户头像
                SizedBox(
                  width: 46.w,
                  height: 46.w,
                  child: CircleAvatar(
                    radius: 23.r,
                    backgroundColor: Colors.white,
                    backgroundImage:
                        user?.avatar != null ? AssetImage(user!.avatar!) : null,
                    child:
                        user?.avatar == null
                            ? Icon(Icons.person, size: 23.w, color: Colors.grey)
                            : null,
                  ),
                ),
              ],
            ],
          ),
          // 时间戳单独一行
          Padding(
            padding: EdgeInsets.only(
              top: 4.h,
              left: isCurrentUser ? 0 : 54.w,
              right: isCurrentUser ? 54.w : 0,
            ),
            child: Text(
              timeStr,
              style: TextStyle(
                fontSize: 12.sp,
                color: Colors.black.withOpacity(0.5),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建输入栏
  Widget _buildInputBar(BuildContext context, GroupChatViewModel viewModel) {
    return Container(
      padding: EdgeInsets.only(
        left: 14.w,
        right: 14.w,
        top: 12.h,
        bottom: 56.h,
      ),
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.3),
        border: Border(
          top: BorderSide(color: Colors.black.withOpacity(0.1), width: 1),
        ),
      ),
      child: Row(
        children: [
          // 输入框
          Expanded(
            child: Container(
              height: 44.w,
              padding: EdgeInsets.only(left: 16.w, right: 8.w),
              decoration: BoxDecoration(
                color: const Color(0xFFFFB181),
                borderRadius: BorderRadius.circular(8.r),
              ),
              child: Row(
                children: [
                  Expanded(
                    child: TextField(
                      controller: viewModel.messageController,
                      decoration: InputDecoration(
                        hintText: 'Send message',
                        hintStyle: TextStyle(
                          fontSize: 16.sp,
                          color: ColorConstants.greyColor,
                        ),
                        border: InputBorder.none,
                        contentPadding: EdgeInsets.zero,
                      ),
                      style: TextStyle(fontSize: 16.sp, color: Colors.black),
                      maxLines: 1,
                      textInputAction: TextInputAction.send,
                      onSubmitted: (_) => viewModel.sendMessage(),
                    ),
                  ),
                  // 发送按钮（在输入框内）
                  GestureDetector(
                    onTap: () => viewModel.sendMessage(),
                    child: Container(
                      width: 32.w,
                      height: 32.w,
                      padding: EdgeInsets.all(4.w),
                      child: Image.asset(
                        'assets/images/send.png',
                        fit: BoxFit.contain,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
